package com.lcz.mytest.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Toast;

import com.lcz.mytest.R;
import com.lcz.mytest.db.UserService;
import com.lcz.mytest.domain.User;
import com.lcz.mytest.utils.LogUtils;
import com.lcz.mytest.utils.SharedPrefsUtil;
import com.lcz.mytest.widget.CustomProgressDialog;
import com.lcz.mytest.widget.ToolBarActivity;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

/**
 * 历史数据图表
 * Created by Administrator on 2016/4/21.
 */
public class PastStockChartActivity extends ToolBarActivity {
    private int MA = 6;
    private CustomProgressDialog loading_dialog;//加载提示
    private WebView webView;
    private SQLiteDatabase db;
    private String stockCode;

    @Override
    protected void findViewById() {
        super.findViewById();
        setContentView(R.layout.activity_stockchart);
        webView = (WebView) findViewById(R.id.wv_showchar);
    }

    @Override
    protected void initView() {
        super.initView();
        if (getIntent().getStringExtra("name") != null) {
            getSupportActionBar().setTitle(getIntent().getStringExtra("name"));
        } else {
            getSupportActionBar().setTitle("代码查询");
        }
        loading_dialog = new CustomProgressDialog(this, "加载中");
        copyDatabase();
        initWebView();
    }

    private void initWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true);// 关键点

        webSettings.setLoadWithOverviewMode(true);
        webSettings.setDisplayZoomControls(false);// 设置显示缩放按钮
        webSettings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        webSettings.setAllowFileAccess(true); // 允许访问文件
        // 支持缩放
        webSettings.setBuiltInZoomControls(true);
        webSettings.setSupportZoom(true);

        webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);// 滚动条风格，为0指滚动条不占用空间，直接覆盖在网页上
        //设置web视图
        webView.setWebChromeClient(new WebChromeClient());
        //加载页面
//        webView.loadUrl("file:///android_asset/echart/tmp.html");
        showchart();
    }

    public void showchart() {
        //股票代码
        String code = getIntent().getStringExtra("symbol");
        stockCode = code;
        final String startdate = getIntent().getStringExtra("startdate");
        final String enddate = getIntent().getStringExtra("enddate");
        if (getIntent().getStringExtra("query") != null) {
            code = getIntent().getStringExtra("query");
        }

        new AsyncTask<String, Integer, String>() {
            protected void onPreExecute() {
                loading_dialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                String code = params[0];
                if (db == null) {
                    db = SQLiteDatabase.openOrCreateDatabase(
                            getDatabasePath("stock").getAbsolutePath(), null);
                }
                // 查询
//                db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
                Cursor cursor = db.query("stock_daydata", null, "code = ?", new String[]{code}, null, null, "date");
                if (startdate != null && enddate != null) {
                    cursor = db.query("stock_daydata", null, "(code = ?)and (date between ? and ?)", new String[]{code, startdate, enddate}, null, null, "date");
                }
                StringBuffer sbTime = new StringBuffer();
                StringBuffer sbData = new StringBuffer();
                StringBuffer sbAverage = new StringBuffer();

                //平均值（收盘价的均价）
                List<Double> aveList = new ArrayList<Double>();
                //收盘价
                List<Double> closeList = new ArrayList<Double>();
                while (cursor.moveToNext()) {
                    // 拼接时间数组
                    String time = cursor.getString(cursor
                            .getColumnIndex("date"));
                    if (sbTime.length() > 0) {
                        sbTime.append(",");
                    }
                    sbTime.append("\"");
                    sbTime.append(time);
                    sbTime.append("\"");

                    double open = cursor.getDouble(cursor
                            .getColumnIndex("open"));
                    double close = cursor.getDouble(cursor
                            .getColumnIndex("close"));
                    double low = cursor.getDouble(cursor.getColumnIndex("low"));
                    double high = cursor.getDouble(cursor
                            .getColumnIndex("high"));

                    if (sbData.length() > 0) {
                        sbData.append(",");
                    }
                    sbData.append("[");
                    sbData.append(open);
                    sbData.append(",");
                    sbData.append(close);
                    sbData.append(",");
                    sbData.append(low);
                    sbData.append(",");
                    sbData.append(high);
                    sbData.append("]");

                    aveList.add(close);
                }
                /*将某一时间段的收盘股价或收盘指数相加的总和，除以时间周期，即得到这一时间的平均线。
                 *如6日移动平均线，就是将近6日的收盘价相加除以6，得到的就是第一个6日平均线的
                 *值 ，再将第一个6日平均线乘以6减去第一日的收盘价加上第7日的收盘价，其总和除以6得到 的就是第二个6日平均线值，
                 *将计算得到的平均数画在坐标图上连成线，即是6日平均线。
                 * */
                for (int i = 0; i < aveList.size(); i++) {
                    double averageCount = 0;
                    int num = aveList.size();
                    closeList.add(aveList.get(i));
                    if (i >= MA) {
                        if (i > MA) {
                            closeList.remove(0);
                        }
                        //保留小数
                        java.text.DecimalFormat myformat = new java.text.DecimalFormat("0.00");
                        averageCount = setAvege(closeList);
                        sbAverage.append(myformat.format(averageCount));
//                        sbAverage.append(averageCount);
                        if (i < num - 1) {
                            sbAverage.append(",");
                        }
                    } else {
                        averageCount = aveList.get(i);
                        sbAverage.append(averageCount);
                        sbAverage.append(",");
                    }
                }

                File dir = getExternalFilesDir(null);
                String path = dir.getAbsolutePath() + "/tmp.html";
                try {
                    InputStream br = getAssets().open("s1.txt");
                    InputStream br2 = new ByteArrayInputStream(code.getBytes());
                    InputStream br3 = getAssets().open("s2.txt");
                    InputStream br4 = new ByteArrayInputStream(sbTime.toString().getBytes());
                    InputStream br5 = getAssets().open("s3.txt");
                    InputStream br6 = new ByteArrayInputStream(sbAverage.toString().getBytes());
                    InputStream br7 = getAssets().open("s4.txt");
                    InputStream br8 = new ByteArrayInputStream(code.getBytes());
                    InputStream br9 = getAssets().open("s5.txt");
                    InputStream br10 = new ByteArrayInputStream(sbData.toString().getBytes());
                    InputStream br11 = getAssets().open("s6.txt");

                    Vector<InputStream> v = new Vector<InputStream>();
                    v.addElement(br);
                    v.addElement(br2);
                    v.addElement(br3);
                    v.addElement(br4);
                    v.addElement(br5);
                    v.addElement(br6);
                    v.addElement(br7);
                    v.addElement(br8);
                    v.addElement(br9);
                    v.addElement(br10);
                    v.addElement(br11);

                    Enumeration<InputStream> e = v.elements();
                    SequenceInputStream sis = new SequenceInputStream(e);
                    OutputStream bw = new FileOutputStream(new File(path));

                    byte[] bys = new byte[1024];
                    int len = 0;
                    while ((len = sis.read(bys)) != -1) {
                        bw.write(bys, 0, len);
                    }
                    br.close();
                    bw.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return path;
            }

            protected void onPostExecute(String result) {
                webView.loadUrl("file:///" + result);
                loading_dialog.dismiss();

            }
        }.execute(code);
    }

    private double setAvege(List<Double> list) {
        if (list == null || list.size() == 0) {
            return 0.00;
        }
        int total = 0;
        for (Double ave : list) {
            total += ave;
        }
        return total * 1f / list.size();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        /*中期线：6d,20d,60d*/
        menu.add(0, 0, 0, "6日均线");
        menu.add(0, 1, 0, "20日均线");
        menu.add(0, 2, 0, "60日均线");
        if (MainActivity.isLogin) {
            menu.add(0, 3, 0, "收藏");
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                Toast.makeText(this, item.toString(), Toast.LENGTH_SHORT).show();
                MA = 6;
                initWebView();
                break;
            case 1:
                Toast.makeText(this, item.toString(), Toast.LENGTH_SHORT).show();
                MA = 20;
                initWebView();
                break;
            case 2:
                Toast.makeText(this, item.toString(), Toast.LENGTH_SHORT).show();
                MA = 60;
                initWebView();
                break;
            case 3:
                new AlertDialog.Builder(this)
                        .setTitle("提示")
                        .setMessage("确认收藏？")
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        //将股票代码添加入相应用户的收藏表中
                                        UserService service = new UserService(PastStockChartActivity.this);
                                        User user = new User();
                                        user.setName(MainActivity.USERNAME);//用户名
                                        user.setStockCode(stockCode);//个股代码
                                        user.setDataType("历史数据");//数据类型
                                        if (service.collect(user)) {
                                            Toast.makeText(PastStockChartActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                                        } else {
                                            Toast.makeText(PastStockChartActivity.this, "系统出错了，请稍后收藏", Toast.LENGTH_SHORT).show();
                                        }
                                    }

                                }).setNegativeButton("取消", null).show();
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    private void copyDatabase() {
        // 获取数据库文件
        final File file = getDatabasePath("stock");
        new AsyncTask<String, Integer, String>() {
            protected void onPreExecute() {
                loading_dialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                if (!file.exists()) {
                    try {
                        InputStream is = getAssets().open("stock");
                        if (!file.getParentFile().exists()) {
                            file.getParentFile().mkdirs();
                        }
                        file.createNewFile();
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] bys = new byte[1024];
                        int len;
                        while ((len = is.read(bys)) != -1) {
                            fos.write(bys, 0, len);
                        }
                        is.close();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return null;
            }

            protected void onPostExecute(String result) {
                loading_dialog.dismiss();
            }
        }.execute();
    }
}
